const _orders = [];
const add = (product) => {
  _orders.push({
    id: product._id,
    product: product,
    amount: 1,
    price: product.price
});
}

const remove = (product) => {
  const index = _orders.findIndex(item => item.product._id === product._id);
  index != -1 && _orders.splice(index, 1);
}

const plus = (product) => {
  const item = has(product);
  if (!item) {
    add(product);
  } else {
    item.amount += 1;
  }
}

const minus = (product) => {
  const item = has(product);
  if (item) {
    item.amount -= 1;
    if (item.amount == 0) {
      remove(product);
    }
  } 
}

const has = (product) => {
  return _orders.find(item => item.product._id === product._id);
}

const get = () => {
  return _orders;
}

const clear = () => {
  _orders = [];
}

const out = () => {
  _orders.forEach(order => {
     order.product.amount -= order.amount;
  });
  _orders = [];
}

const count = () => {
  return _orders.length;
}

const total = () => {
  return _orders.reduce((acc, cur) => {
      return acc + cur.price * cur.amount;
  },0);
}

module.exports = {
  get: get,
  plus: plus,
  minus: minus,
  clear: clear,
  count: count,
  total: total
}